﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.Mc.Common.FaceEnginePoll;

namespace One2One
{
    public class One2OneHelper
    {
        #region constructor

        private One2OneHelper()
        {
            LinqFaceEnginePollManager<FaceEnginePollItem>.Instance.Init(4);
        }

        #endregion

        #region fileds

        public static One2OneHelper Instance = new One2OneHelper();

        static log4net.ILog _log = log4net.LogManager.GetLogger(typeof(One2OneHelper));

        #endregion

        #region public methods

        public float GetSimlarByUrl(string message)
        {
            FaceCompareByUrlRequest param = null;
            try
            {
                param = Newtonsoft.Json.JsonConvert.DeserializeObject<FaceCompareByUrlRequest>(message);
            }
            catch(Exception ex)
            {
                _log.Error(ex);
            }
            if (param != null && param.url1 != null && param.url2 != null)
            {
                var image1 = Util.GetImageByUrl(param.url1);
                var image2 = Util.GetImageByUrl(param.url2);

                if (image1 != null && image2 != null)
                {
                    try
                    {
                        return Util.GetSimilar(image1, image2);

                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex);
                    }
                }
            }
            return 0;
        }

        public float GetSimlarByBase64(string message)
        {
            if (!string.IsNullOrEmpty(message))
            {
                FaceCompareRequest param = null;
                try
                {
                    param = Newtonsoft.Json.JsonConvert.DeserializeObject<FaceCompareRequest>(message);
 
                }
                catch(Exception ex)
                {
                    _log.Error(ex);
                }

                if (param != null && param.faceimage1 != null && param.faceimage2 != null)
                {
                    byte[] image1 = null;
                    byte[] image2 = null;
                    _log.Info(param.faceimage1);
                    _log.Info(param.faceimage2);
                    try
                    {
                        image1 = Convert.FromBase64String(param.faceimage1.Replace(" ", "+"));
                        image2 = Convert.FromBase64String(param.faceimage2.Replace(" ", "+"));
                        if (image1 != null && image2 != null)
                        {

                            return Util.GetSimilar(image1, image2);
                        }

                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex);
                    }

                }
            }
            
            
            return 0;
        }

        #endregion
    }
}
